<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="所属班级">
            <class-tree v-model="queryParams.belongId" gradeDisabled />
          </el-form-item>
          <el-form-item label="任课老师" prop="teacherName">
            <el-input v-model="queryParams.teacherName" placeholder="请输入任课老师" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="点名时间" style="width: 450px">
            <el-date-picker
              v-model="rangeTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="3">
            <span style="color: blue">应到：{{ bookStat.attendanceNum }}</span>
          </el-col>
          <el-col :span="3">
            <span style="color: green">实到：{{ bookStat.presenceNum }}</span>
          </el-col>
          <el-col :span="6">
            <span style="color: yellowgreen">请假：{{ bookStat.leaveNum + ' ' + bookStat.leaveList }}</span>
          </el-col>
          <el-col :span="6">
            <span style="color: red">缺勤：{{ bookStat.absenceNum + ' ' + bookStat.absenceList }}</span>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table height="calc(100vh - 370px)" stripe v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
        <el-table-column label="姓名" align="center" prop="studentName" />
        <el-table-column label="学号" align="center" prop="studentNo" />
        <el-table-column label="所属班级" align="center" prop="className" />
        <el-table-column label="住宿类型" align="center" prop="accommodationType">
          <template #default="scope">
            <dict-tag :options="student_accommodation_type" :value="scope.row.accommodationType" />
          </template>
        </el-table-column>
        <el-table-column label="在班状态" align="center" prop="attendanceStatus">
          <template #default="scope">
            <dict-tag :options="class_book_status" :value="scope.row.attendanceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="任课老师" align="center" prop="teacherName" />
        <el-table-column label="点名时间" align="center" prop="bookTime" />
      </el-table>
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="ClassBook" lang="ts">
import { listClassInfo } from '@/api/office/class';
import {
  listClassBook4Call, pageClassBookCall
} from '@/api/attendance/class/book';
import { ClassBookVO, ClassBookQuery, ClassBookForm } from '@/api/attendance/class/book/types';
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { student_accommodation_type, class_book_status, student_subscribe_status, student_school_status } = toRefs<any>(
  proxy?.useDict('student_accommodation_type', 'class_book_status', 'student_subscribe_status', 'student_school_status')
);

const bookList = ref<ClassBookVO[]>([]);
const bookStat = ref({
  attendanceNum: 0,
  presenceNum: 0,
  leaveNum: 0,
  leaveList: '',
  absenceNum: 0,
  absenceList: ''
});
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const rangeTime = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const studentFormRef = ref<ElFormInstance>();
const classOptions = ref<any[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ClassBookForm = {
  id: undefined,
  studentId: undefined,
  studentName: undefined,
  accommodationType: undefined,
  classId: undefined,
  className: undefined,
  attendanceStatus: undefined,
  teacherId: undefined,
  teacherName: undefined,
  bookTime: undefined,
  remark: undefined
};
const data = reactive<PageData<ClassBookForm, ClassBookQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    studentName: undefined,
    accommodationType: undefined,
    classId: undefined,
    className: undefined,
    attendanceStatus: undefined,
    teacherId: undefined,
    teacherName: undefined,
    bookTime: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生id不能为空', trigger: 'blur' }],
    studentName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
    accommodationType: [{ required: true, message: '住宿类型不能为空', trigger: 'change' }],
    classId: [{ required: true, message: '班级id不能为空', trigger: 'blur' }],
    className: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
    attendanceStatus: [{ required: true, message: '出勤状态不能为空', trigger: 'change' }],
    teacherId: [{ required: true, message: '任课老师staff_id不能为空', trigger: 'blur' }],
    teacherName: [{ required: true, message: '任课老师姓名不能为空', trigger: 'blur' }],
    bookTime: [{ required: true, message: '点名时间不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const handleNodeClick = (data: any) => {
  if (data?.id?.startsWith('grade')) return;
  queryParams.belongId = data.id;
};

/** 查询学生信息列表 */
const getList = async () => {
  loading.value = true;
  proxy?.addDateRange(queryParams.value, rangeTime.value, 'BookTime');
  queryParams.value.bookTime = parseTime(new Date(), '{y}-{m}-{d}');
  const res = await pageClassBookCall(queryParams.value);
  bookList.value = res.rows;
  total.value = res.total;
  calBookStat(bookList.value);
  loading.value = false;
};

const calBookStat = (books: any[]) => {
  let attendanceNum = books?.length;
  let presenceNum = 0;
  let leaveNum = 0;
  let leaveList: [] = [];
  let absenceNum = 0;
  let absenceList: [] = [];
  if (books) {
    for (let book of books) {
      if (book.attendanceStatus === '1' || book.attendanceStatus === '2') {
        presenceNum += 1;
      } else if (book.attendanceStatus === '3') {
        absenceNum += 1;
        absenceList.push(book.studentName);
      } else if (book.attendanceStatus === '4') {
        leaveNum += 1;
        leaveList.push(book.studentName);
      }
    }
  }
  bookStat.value = {
    attendanceNum: attendanceNum,
    presenceNum: presenceNum,
    leaveNum: leaveNum,
    leaveList: leaveList.length > 0 ? '(' + leaveList.join('、') + ')' : '',
    absenceNum: absenceNum,
    absenceList: absenceList.length > 0 ? '(' + absenceList.join('、') + ')' : ''
  };
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  studentFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  rangeTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ClassBookVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const searchClassInfo = (queryString, cb) => {
  listClassInfo({ className: queryString }).then((response) => {
    cb(response.rows);
  });
};

onMounted(() => {
  // getClassTree();
  getList();
});
</script>
